package com.kitty.game.activity.service.task;

import com.kitty.common.utils.SpringUtils;
import com.kitty.game.activity.model.product.ActivityType;
import com.kitty.game.boss.config.BossSet;
import com.kitty.game.boss.model.BossFightParam;
import com.kitty.game.boss.model.BossNpcParam;
import com.kitty.game.boss.model.BossParam;
import com.kitty.game.boss.service.NewBossService;
import com.kitty.game.config.NPC;
import com.kitty.game.config.TaskSet;
import com.kitty.game.fight.bean.Fight;
import com.kitty.game.i18n.I18nId;
import com.kitty.game.i18n.I18nIdDataPool;
import com.kitty.game.npc.model.NpcButton;
import com.kitty.game.party.model.Party;
import com.kitty.game.role.model.Role;
import com.kitty.game.task.message.vo.TaskInfo;
import com.kitty.game.task.model.product.TaskType;
import com.kitty.game.team.message.RespMsg;
import com.kitty.game.team.model.Team;
import com.kitty.game.utils.Const;
import com.kitty.listener.event.FightEndEvent;
import com.kitty.mina.message.MessagePusher;
import org.nutz.lang.util.NutMap;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
//后加


/**
 * 帮派日常挑战处理类
 */
@Component
public class PartyDailyTaskHandler extends TaskActivityHandler {
    private final int TASKID_AT_NPC = 2200;
    private static final int ACCEPT_MIN_LEVEL = 40;
    private static final String ACCEPT_SUCESS = "领取挑战成功，快去和#Y{0}#n切磋吧！[前往挑战/" + NpcButton.PARTY_DAILY_TASK_AUTOWALK.getKey() + "][离开]";
    private static final String FIGHT_SUCESS = "还是有两下子的嘛，恭喜挑战成功！[继续挑战/" + NpcButton.PARTY_DAILY_TASK_AUTOWALK.getKey() + "][离开]";
    private static final String FIGHT_SUCESS_NO_NEXT = "还是有两下子的嘛，恭喜挑战成功！[离开]";
    private static final String FIGHT_FAIL = "你的实力太弱了，还是练练再来吧！[重新挑战/" + NpcButton.PARTY_DAILY_TASK_AUTOWALK.getKey() + "][离开]";

    @Override
    public boolean acceptTaskAtNpc(Role role, NPC npc, boolean auto) {
        boolean accepted = super.acceptTaskAtNpc(role, npc, auto);
        if (accepted == false) {
            return false;
        }

        TaskSet taskSet = getTaskSetByType(role);
        String content = MessageFormat.format(ACCEPT_SUCESS, taskSet.getNpcName());
        sendNpcContent(role, npc, content);

        return true;
    }

    @Override
    public TaskSet getAcceptingTask(Role role, NPC npc) {
        return taskService.getTaskSet(TASKID_AT_NPC, role);
    }

    @Override
    public String canAcceptTask(Role role, TaskSet taskSet, boolean auto) {
        if (role.getLevel() < ACCEPT_MIN_LEVEL) {
            MessagePusher.notify2Player(role, I18nId.PMT_364, ACCEPT_MIN_LEVEL);
            return "";
        }
        if (teamService.isInTeam(role)) {
            Team team = teamService.getTeam(role.getRoleId());
            String names = teamService.checkMember(team, memberRole -> memberRole.getLevel() < ACCEPT_MIN_LEVEL);
            if (names != null) {
                String content = I18nIdDataPool.getI18nContent(I18nId.PMT_366, names, ACCEPT_MIN_LEVEL);
                teamService.pushMessageToTeam(team, new RespMsg(content));
                return "";
            }
        }

        /**是否已经完成*/
        if (isAcceptedTask(role)) {
            MessagePusher.notify2Player(role, I18nId.PMT_365);
            return "";
        }

        /**是否还有剩余次数*/
        Party party = SpringUtils.getPartyService().getParty(role);
        if (party == null) {
            MessagePusher.pushMessage(role, new RespMsg("当前没有帮派。"));
            return "";
        }
        if (SpringUtils.getPartyService().getPartyMember(party, role) == null) {
            MessagePusher.pushMessage(role, new RespMsg("当前没有帮派。"));
            return "";
        }
        int finishCount = SpringUtils.getActivityService().getFinishCount(role, ActivityType.PARTY_DAILY_TASK);
        int maxCount = party.getLevel();
        boolean haveRemainCount = finishCount >= maxCount ? false : true;
        if (haveRemainCount == false) {
            MessagePusher.notify2Player(role, I18nId.PMT_367, maxCount);
            return "";
        }

        return null;
    }

    @Override
    public boolean isMemberAcceptTask(Role role, TaskSet taskSet) {
        return isAcceptedTask(role) ? false : true;
    }

    @Override
    public boolean isMemberSubmitTask(Role role, TaskSet taskSet) {
        TaskSet acceptedTaskSet = getTaskSetByType(role);
        if (acceptedTaskSet != null && taskSet != null
                && acceptedTaskSet.getId() == taskSet.getId()) {
            return true;
        }

        return false;
    }

    private boolean isAcceptedTask(Role role) {
        if (getTaskSetByType(role) != null) {
            return true;
        }
        return false;
    }

    @Override
    public TaskInfo getTaskInfo(Role role, TaskSet taskSet) {
        return taskService.getTaskInfo(role, taskSet);
    }

    @Override
    public String getPrompt(NPC npc) {
        return null;
    }

    @Override
    public BossNpcParam newBossNpcParam(Role role, TaskSet taskSet) {
        return null;
    }

    @Override
    public String getNpcContent(Role role, NPC bossNpc) {
        return null;
    }

    @Override
    public TaskType getTaskType() {
        return TaskType.PARTY_DAILY;
    }

    @Override
    public String getNpcContentNotFight(Role role, NPC bossNpc) {
        return null;
    }

    @Override
    public void doStartFight(Role role, TaskSet taskSet, NPC bossNpc) {
        /**随机任务类型*/
        ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current();
        int rand = threadLocalRandom.nextInt(3);
        switch (rand) {
            case 0: {
                fightType1(role, taskSet, bossNpc);
                break;
            }
            case 1: {
                fightType2(role, taskSet, bossNpc);
                break;
            }
            case 2: {
                fightType3(role, taskSet, bossNpc);
                break;
            }
        }


    }

    /**第1种帮派日常任务类型，正常战斗，死亡时有死亡惩罚*/
    private void fightType1(Role role, TaskSet taskSet, NPC bossNpc) {
        List<BossParam> bossParamList = new ArrayList<>();
        int count = 5;

        BossSet bossSet = null;
        NewBossService bossService = SpringUtils.getBossService();
        for (int i = 0; i < count; i++) {
            String bossName = "帮派日常陪练1";
            bossSet = bossService.getBossSet(bossName);
            bossParamList.add(new BossParam(bossSet, "帮派日常陪练"));
        }
        BossFightParam bossFightParam = new BossFightParam(bossParamList, getFightType(role), taskSet.getId(), bossNpc.getId());
        bossFightParam.setShoutingList(Arrays.asList("#R战斗结束时死亡的角色会受到惩罚。#n", "战胜我们就算挑战成功！"));
        bossService.startFightToBoss(role, bossFightParam);
        teamService.pushMessage(role, new RespMsg("#R本场战斗会有死亡惩罚，请小心！#n"));
    }

    /**第2种帮派日常任务类型，猜真假*/
    private void fightType2(Role role, TaskSet taskSet, NPC bossNpc) {
        List<BossParam> bossParamList = new ArrayList<>();
        int count = 10;
        ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current();
        int rand = threadLocalRandom.nextInt(count);

        BossSet bossSet = null;
        NewBossService bossService = SpringUtils.getBossService();
        for (int i = 0; i < count; i++) {
            String bossName = "猜真假考官";
            bossSet = bossService.getBossSet(bossName);
            BossParam bossParam = new BossParam(bossSet, "猜真假考官");
            if (i == rand) {
                bossParam.setLife(1);
            } else {
                bossParam.setLife(Integer.MAX_VALUE);
            }
            bossParamList.add(bossParam);
        }

        String msg = "我们之中有一个是假的，只要你对我们进行#R物理攻击#n就能找到假的了，你还有#R%s#n回合机会！";
        int maxRound = 5;
        String message = String.format(msg, maxRound);
        BossFightParam bossFightParam = new BossFightParam(bossParamList, getFightType(role), taskSet.getId(), bossNpc.getId());
        bossFightParam.setShoutingList(Arrays.asList(message));
        bossFightParam.setLoadGuard(false);

        Fight fight = bossService.startFightToBoss(role, bossFightParam);
        if (fight.getData() == null) {
            fight.setData(NutMap.NEW());
        }
        fight.getData().setv("fight_guess_true", true);
        fight.getData().setv("fight_round_start_shouting", Arrays.asList(msg));
        fight.setMaxRound(maxRound);
    }

    /**第3种帮派日常任务类型，按顺序打倒目标对象*/
    private void fightType3(Role role, TaskSet taskSet, NPC bossNpc) {
        List<BossParam> bossParamList = new ArrayList<>();
        int count = 10;

        BossSet bossSet = null;
        NewBossService bossService = SpringUtils.getBossService();
        bossSet = bossService.getBossSet("挑战使者");
        BossParam bossParam = new BossParam(bossSet, "挑战使者");
        bossParam.setLife(Integer.MAX_VALUE);
        bossParamList.add(bossParam);

        ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current();
        List<String> list = Arrays.asList("帮派日常名字1", "帮派日常名字2", "帮派日常名字3", "帮派日常名字4", "帮派日常名字5");
        List<String> nameList = Arrays.asList("空山新雨后天气晚来秋","明月松间照清泉石上流","红豆生南国春来发几枝","野火烧不尽春风吹又生");
        int index = threadLocalRandom.nextInt(nameList.size());
        String line = nameList.get(index);
        List<String> names = new ArrayList<>();
        for (int i=0; i<line.length()-1; i++) {
            String substring = line.substring(i, i + 1);
            names.add(substring);
        }
        ArrayList<String> orderNames = new ArrayList<>(names.subList(0, 5));
        for (int i = 1; i < count; i++) {
            index = threadLocalRandom.nextInt(list.size());
            String bossName = list.get(index);
            bossSet = bossService.getBossSet(bossName);

            String name = names.remove(threadLocalRandom.nextInt(names.size()));
            bossParam = new BossParam(bossSet, name);
            bossParam.setLife(Integer.MAX_VALUE);

            bossParamList.add(bossParam);
        }

        String msg = "#R" + line.substring(0, 5) + "#n。按顺序打倒对应名字的陪练，就当你赢了。剩余回合数#R%s#n。";
        int maxRound = 5;
        String message = String.format(msg, maxRound);

        BossFightParam bossFightParam = new BossFightParam(bossParamList, getFightType(role), taskSet.getId(), bossNpc.getId());
        bossFightParam.setShoutingList(Arrays.asList(message));
        bossFightParam.setLoadGuard(false);

        Fight fight = bossService.startFightToBoss(role, bossFightParam);

        if (fight.getData() == null) {
            fight.setData(NutMap.NEW());
        }
        fight.getData().setv("fight_order_target", true);
        fight.getData().setv("fight_order_target_name", orderNames);
        fight.getData().setv("fight_order_target_dead_name", new ArrayList<String>(maxRound));
        fight.getData().setv("fight_round_start_shouting", Arrays.asList(msg));
        fight.setMaxRound(maxRound);
    }

    @Override
    protected int getFightType(Role role) {
        return Const.fightType_partyDaily;
    }

    @Override
    protected void addActivityFinishCount(Role role, TaskSet taskSet) {
        /**最后一个日常挑战任务时，加次数*/
        if (taskService.getNextTask(taskSet, role) == null) {
            SpringUtils.getActivityService().addFinishCount(role, ActivityType.PARTY_DAILY_TASK, 1);
        }
    }

    @Override
    protected void giveReward(Role role, NutMap reward, TaskSet taskSet, int currPetId) {
        if (SpringUtils.getActivityService().getFinishCount(role, ActivityType.PARTY_DAILY_TASK) > ActivityType.PARTY_DAILY_TASK.getTotalCount()) {return;}

        /**最后一个日常挑战任务时，才给奖励*/
        if (taskService.getNextTask(taskSet, role) == null) {
            taskService.giveAward(role, taskSet);
        }
    }

    @Override
    protected void doBeforeDelete(Role role, TaskSet taskSet) {

    }

    @Override
    protected void doAfterDelete(Role role, TaskSet taskSet) {
        /**胜利提示*/
        String content = null;
        TaskSet nextTaskSet = taskService.getNextTask(taskSet, role);
        if (nextTaskSet != null) {
            acceptTask(role, nextTaskSet, false);
            content = FIGHT_SUCESS;
        } else {
            content = FIGHT_SUCESS_NO_NEXT;
        }

        NPC npc = SpringUtils.getMapService().getNpcByName(taskSet.getNpcName());
        if (npc != null) {
            sendNpcContent(role, npc, content);
        }
    }

    @Override
    public boolean isCreateNpcForFight(TaskSet taskSet) {
        return false;
    }

    @Override
    public void doFightFail(Role role, TaskSet taskSet, FightEndEvent fightEndEvent) {
        super.doFightFail(role, taskSet, fightEndEvent);
        /**死亡提示与惩罚*/
        NPC npc = SpringUtils.getMapService().getNpc(fightEndEvent.getNpcId());
        if (npc != null) {
            sendNpcContent(role, npc, FIGHT_FAIL);
        }

        teamService.memberHandleThreadLocal(role, memberRole -> SpringUtils.getRoleService().punishFightDead(memberRole));
    }
}
